<template>
  <van-uploader
    v-model="fileList"
    :multiple="multiple"
    :before-read="beforeRead"
    :after-read="afterRead"
    :max-count="maxCount"
    name="multipartFile"
    :preview-size="previewSize"
  >
    <!-- 上传文件类型的自定义样式 -->
    <div v-if="custom == 'file'">
      <van-button icon="plus" type="primary">上传文件</van-button>
    </div>
    <div class="uploadBox" v-else>
      <van-icon size="30px" name="photo-o" />
      <span style="margin-top: 2px">添加图片</span>
    </div>
  </van-uploader>
</template>
<script>
import cfg from "@/config";
export default {
  data() {
    return {
      fileList: [],
      cfg,
    };
  },
  props: {
    multiple: {
      type: Boolean,
      default: false,
    },
    type: {
      type: String,
      default: "OTHER",
    },
    maxCount: {
      type: Number,
      default: 1,
    },
    previewSize: {
      type: String,
      default: "100px",
    },
    custom: {
      type: String,
      default: "",
    },
    //只是为了记录动态渲染上传组件的时候是哪个索引
    index: {
      type: Number,
      default: 0,
    },
    isCheck: {
      type: Boolean,
      default: false,
    },
    activeCover: {
      type: String,
      default: "",
    },
     fileList: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  watch: {
    activeCover(val) {
      console.log(val, "val");
      if (val) {
        this.fileList = [{ url: val }];
      } else {
        this.fileList = [];
      }
    },
    fileList(val) {
      this.fileList = val;
    },
  },
  methods: {
    beforeRead(file) {
      console.log(file);
      return true;
    },
    afterRead(fileObj) {
      const fileArr = Array.isArray(fileObj) ? fileObj : [fileObj];
      fileArr.map((s, i) => {
        console.log(s, i);
        s.status = "uploading";
        s.message = "上传中...";
        const file = s.file;
        const uploadData = new window.FormData();
        uploadData.append("multipartFile", file);
        console.log(this.cfg.baseUrl);
        this.$api("/resource/upload?type=" + this.type, uploadData, {
          method: "post",
        })
          .then((res) => {
            console.log(res);
            s.status = "done";
            s.message = "上传成功";
            s.url = res;
            console.log(this.fileList);
            if (this.isCheck) {
              this.$emit("handleSuccess", this.fileList, this.index);
            } else {
              this.$emit("handleSuccess", this.fileList);
            }
          })
          .catch((err) => {
            console.log(err);
            s.status = "failed";
            s.message = "上传失败";
          });
        return s;
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.uploadBox {
  width: 87px;
  height: 87px;
  background: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  color: #999;
  font-size: 12px;
}
// ::v-deep .van-uploader__preview-image {
//   height: 87px !important;
// }
</style>